<template>
  <div class="order-manage">
    <div class="page-header">
      <div class="header-title">订单管理</div>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="输入订单号"></el-input>
        </el-form-item>
        <el-form-item label="所属餐厅">
          <el-select v-model="searchForm.restaurantId" placeholder="请选择" clearable style="width: 200px;">
            <el-option
              v-for="item in restaurantOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待支付" :value="0"></el-option>
            <el-option label="已支付" :value="1"></el-option>
            <el-option label="配送中" :value="2"></el-option>
            <el-option label="已完成" :value="3"></el-option>
            <el-option label="已取消" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="orderList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
      <el-table-column prop="restaurantName" label="餐厅名称" width="150"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="receiverName" label="收货人" width="100"></el-table-column>
      <el-table-column prop="receiverPhone" label="联系电话" width="150"></el-table-column>
      <el-table-column prop="payAmount" label="订单金额" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.payAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewOrderDetail(scope.row.id)">查看详情</el-button>
          <el-button 
            v-if="scope.row.status === 1" 
            size="mini" 
            type="primary" 
            @click="handleDeliveryOrder(scope.row)"
          >
            配送
          </el-button>
          <el-button 
            v-if="scope.row.status === 2" 
            size="mini" 
            type="success" 
            @click="handleCompleteOrder(scope.row)"
          >
            完成
          </el-button>
          <el-button 
            v-if="scope.row.status < 3" 
            size="mini" 
            type="danger" 
            @click="handleCancelOrder(scope.row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="70%">
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatDate(currentOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(currentOrder.status)" size="small">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </div>
          <div v-if="currentOrder.payTime" class="detail-item">
            <span class="label">支付时间：</span>
            <span>{{ formatDate(currentOrder.payTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">支付方式：</span>
            <span>{{ getPayTypeText(currentOrder.payType) }}</span>
          </div>
          <div v-if="currentOrder.remark" class="detail-item">
            <span class="label">备注：</span>
            <span>{{ currentOrder.remark }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>用户信息</h4>
          <div class="detail-item">
            <span class="label">用户名：</span>
            <span>{{ currentOrder.username }}</span>
          </div>
          <div class="detail-item">
            <span class="label">用户ID：</span>
            <span>{{ currentOrder.userId }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>配送信息</h4>
          <div class="detail-item">
            <span class="label">收货人：</span>
            <span>{{ currentOrder.receiverName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ currentOrder.receiverPhone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">配送地址：</span>
            <span>{{ currentOrder.receiverAddress }}</span>
          </div>
          <div v-if="currentOrder.deliveryTime" class="detail-item">
            <span class="label">配送时间：</span>
            <span>{{ formatDate(currentOrder.deliveryTime) }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>餐厅信息</h4>
          <div class="detail-item">
            <span class="label">餐厅名称：</span>
            <span>{{ currentOrder.restaurantName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">餐厅ID：</span>
            <span>{{ currentOrder.restaurantId }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="currentOrder.orderItems" border>
            <el-table-column prop="dishName" label="商品名称"></el-table-column>
            <el-table-column label="商品图片" width="120">
              <template slot-scope="scope">
                <el-image
                  style="width: 60px; height: 60px"
                  :src="scope.row.dishImage"
                  fit="cover"
                  :preview-src-list="[scope.row.dishImage]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="dishPrice" label="单价" width="100">
              <template slot-scope="scope">¥{{ scope.row.dishPrice }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
            <el-table-column label="小计" width="100">
              <template slot-scope="scope">¥{{ scope.row.dishPrice * scope.row.quantity }}</template>
            </el-table-column>
          </el-table>
          
          <div class="order-summary">
            <div class="summary-item">
              <span>商品总价：</span>
              <span>¥{{ currentOrder.totalAmount }}</span>
            </div>
            <div class="summary-item">
              <span>配送费：</span>
              <span>¥{{ currentOrder.deliveryFee }}</span>
            </div>
            <div class="summary-item total">
              <span>实付金额：</span>
              <span>¥{{ currentOrder.payAmount }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OrderManage',
  data() {
    return {
      loading: false,
      orderList: [],
      restaurantOptions: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        orderNo: '',
        restaurantId: '',
        status: ''
      },
      dialogVisible: false,
      currentOrder: null
    }
  },
  created() {
    this.fetchRestaurantOptions()
    this.fetchOrderList()
    
    // 如果URL中有订单ID，自动打开订单详情
    if (this.$route.query.id) {
      this.viewOrderDetail(this.$route.query.id)
    }
  },
  methods: {
    fetchRestaurantOptions() {
      this.$http.get('/admin/restaurant')
        .then(response => {
          this.restaurantOptions = response.data.data
        })
        .catch(error => {
          this.$message.error('获取餐厅列表失败')
          console.error('获取餐厅列表失败', error)
        })
    },
    fetchOrderList() {
      this.loading = true
      
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        restaurantId: this.searchForm.restaurantId,
        status: this.searchForm.status,
        orderNo: this.searchForm.orderNo
      }
      
      this.$http.get('/admin/order/list', { params })
        .then(response => {
          const { data } = response.data
          this.orderList = data.records
          this.total = data.total
        })
        .catch(error => {
          this.$message.error('获取订单列表失败')
          console.error('获取订单列表失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchOrderList()
    },
    resetSearch() {
      this.searchForm = {
        orderNo: '',
        restaurantId: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrderList()
    },
    handleCurrentChange() {
      this.fetchOrderList()
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || 'info'
    },
    getPayTypeText(payType) {
      const payTypeMap = {
        1: '微信支付',
        2: '支付宝',
        3: '余额支付'
      }
      return payTypeMap[payType] || '未知支付方式'
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    viewOrderDetail(orderId) {
      this.$http.get(`/admin/order/${orderId}`)
        .then(response => {
          this.currentOrder = response.data.data
          this.dialogVisible = true
        })
        .catch(error => {
          this.$message.error('获取订单详情失败')
          console.error('获取订单详情失败', error)
        })
    },
    handleDeliveryOrder(order) {
      this.$confirm('确认将订单状态更改为配送中？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateOrderStatus(order.id, 2)
      }).catch(() => {})
    },
    handleCompleteOrder(order) {
      this.$confirm('确认将订单状态更改为已完成？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateOrderStatus(order.id, 3)
      }).catch(() => {})
    },
    handleCancelOrder(order) {
      this.$confirm('确认取消该订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateOrderStatus(order.id, 4)
      }).catch(() => {})
    },
    updateOrderStatus(orderId, status) {
      this.$http.put(`/admin/order/${orderId}/status`, null, {
        params: { status }
      })
        .then(() => {
          this.$message.success('订单状态更新成功')
          this.fetchOrderList() // 刷新列表
          
          // 如果当前正在查看该订单详情，刷新详情
          if (this.dialogVisible && this.currentOrder && this.currentOrder.id === orderId) {
            this.viewOrderDetail(orderId)
          }
        })
        .catch(error => {
          this.$message.error((error.response && error.response.data && error.response.data.message) || '更新订单状态失败')
        })
    }
  }
}
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 订单详情样式 */
.order-detail {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item .label {
  width: 100px;
  color: #909399;
  font-weight: bold;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.summary-item {
  margin-bottom: 10px;
}

.summary-item.total {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}
</style>
